package com.example.home.view

import android.os.Bundle
import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnScrollListener
import androidx.recyclerview.widget.SimpleItemAnimator
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.Glide
import com.example.base.app.RouterPath
import com.example.common.cache.RecyclerCachePool
import com.example.common.entity.SimpleVideoEntity
import com.example.common.mvi.BaseMviFragment
import com.example.home.R
import com.example.home.adapter.HomeVideoListAdapter
import com.example.home.databinding.FragmentHomeListBinding
import com.example.home.intent.HomeViewIntent
import com.example.home.state.HomeUiState
import com.example.home.vm.HomeViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
class HomeListFragment : BaseMviFragment<FragmentHomeListBinding>() {
    private val mViewModel:HomeViewModel by activityViewModels()
    private var typeId =0
    private var pageIndex =1
    private var pageSize =10
    private var channelId = ""
    private var simpleVideoList=mutableListOf<SimpleVideoEntity>()
    private lateinit var videoListAdapter:HomeVideoListAdapter

    private lateinit var videoCommentListDialog: VideoCommentListDialog

    companion object{
        @JvmStatic
        fun newInstance(channelId:String,typeId: Int) = HomeListFragment().apply {
            arguments = Bundle().apply {
                putString("channelId",channelId)
                putInt("typeId",typeId)
            }
        }
    }
    override fun getLayoutId(): Int =R.layout.fragment_home_list

    override fun initViews() {
        //获取传递进来的参数
        arguments?.let {
            channelId = it.getString("channelId").toString()
            typeId = it.getInt("typeId")
        }
        //下拉刷新事件
        mDataBinding.refreshLayout.setOnRefreshListener {
           if (simpleVideoList.size==0 || pageIndex>1){
               pageIndex = 1
               loadData()
           }else{
               mDataBinding.refreshLayout.finishRefresh()
           }
        }
        videoListAdapter=HomeVideoListAdapter(simpleVideoList).apply {
            //itemViewCache=HomeItemCache()
            preloadEndCount=4
            preloadMoreData={
                pageIndex+=1
                loadData()
            }
            //添加点击事件
            setOnItemClickListener(object : HomeVideoListAdapter.OnItemClickListener{
                override fun onItemChick(v: View, position: Int) {
                    when(v.id){
                        R.id.iv_video_play -> {
                            ARouter.getInstance().build(RouterPath.PATH_PLAY_PAGE)
                                .withString("videoPath",simpleVideoList[position].videopath)
                                .withString("userId",simpleVideoList[position].userid)
                                .withString("itemId",simpleVideoList[position].item_id)
                                .withInt("typeId",typeId)
                                .withInt("moduleType",0)
                                .withString("channelId",channelId)
                                .navigation()
                        }
                        R.id.iv_commend -> {
                            videoCommentListDialog=VideoCommentListDialog(simpleVideoList[position].item_id)
                            videoCommentListDialog.show(this@HomeListFragment.childFragmentManager,"VideoCommendDialog")
                        }
                        R.id.iv_more-> {
                            this@HomeListFragment.showToastMsg("正在开发，敬请期待！")
                        }
                    }
                }

            })
        }
       // itemCache=HomeItemCache()
        mDataBinding.rvVideoList.run {
            //设置屏幕外缓存ViewHolder的数量，默认为2
            setItemViewCacheSize(12)
            //防止Item组件重复测量(适用于大小固定子组件)
            setHasFixedSize(true)
            //设置缓存池大小
            setRecycledViewPool(RecyclerCachePool)

            addOnScrollListener(object :OnScrollListener(){
                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    super.onScrollStateChanged(recyclerView, newState)
                    if(newState==RecyclerView.SCROLL_STATE_IDLE){
                        //回复图片加载
                        Glide.with(this@HomeListFragment).resumeRequests()
                    }else{
                        //暂停图片加载
                        Glide.with(this@HomeListFragment).pauseRequests()
                    }
                }
            })
            //关闭不必要的动画
            (itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
            adapter=videoListAdapter
            layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        }
    }

//    override fun onDestroyView() {
//        videoCommentListDialog.dismiss()
//        videoCommentListDialog.onDestroyView()
//        super.onDestroyView()
//    }
    fun lazyLoadData() {
        //如果数据类型与传递进来的channelId不一致，需要清理掉后再加载
        if (simpleVideoList.size > 0 && simpleVideoList[0].channelid != channelId){
            simpleVideoList.clear()
            videoListAdapter.notifyDataSetChanged()
        }
        loadData()
    }
    private fun loadData() {
        lifecycleScope.launch {
            if (typeId ==-1){
                mViewModel.channel.send(HomeViewIntent.LoadRecommendSimpleVideoList(pageIndex,pageSize))
            }else{
                mViewModel.channel.send(HomeViewIntent.LoadSimpleVideoListById(channelId,pageIndex,pageSize))
            }
        }
    }
    override suspend fun collectUIState() {
        super.collectUIState()
        mViewModel.uiStateFlow.collect{
            when(it){
                is HomeUiState.LoadSimpleVideoSuccess -> updatePageData(it.list)
                is HomeUiState.LoadSimpleVideoFail -> {
                    //回退到上一页
                    if (pageIndex > 1){
                        pageIndex -= 1
                    } else {
                        mDataBinding.refreshLayout.finishRefresh()
                        simpleVideoList.clear()
                        videoListAdapter.notifyDataSetChanged()
                    }
                }
                else -> {}
            }
        }
    }
    private fun updatePageData(list: List<SimpleVideoEntity>) {
        //如果下拉刷新获取第一页，需要清理
        if (pageIndex == 1){
            mDataBinding.refreshLayout.finishRefresh()
            simpleVideoList.clear()
        }
        simpleVideoList.addAll(list)
        videoListAdapter.notifyDataSetChanged()
    }
}